package com.yichuang.security.jwt.main.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yichuang.security.jwt.main.service.OAuth2Service;
import com.yichuang.security.jwt.main.utils.JwtAccessTokenConverterUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p> 鉴权调试接口 </p>
 *
 * @author tuonioooo
 * @site https://miliqkdoc.motopa.cn/
 * @date 2020/6/18 11:20
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class OAuth2Controller {

    private final OAuth2Service oAuth2Service;

    @GetMapping("/login/{id}")
    public String login(@PathVariable String id) {
        return "login id : " + id;
    }

    @GetMapping("/product/{id}")
    public String getProduct(@PathVariable String id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info(JSON.toJSONString(authentication));
        return "product id : " + id;
    }

    @GetMapping("/order/{id}")
    public String getOrder(@PathVariable String id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info(JSON.toJSONString(authentication));
        return "order id : " + id;
    }

    @GetMapping("/oauth2/getToken")
    public String login() {
        String token = oAuth2Service.getToken("user", "password");
        JSONObject jsonObject = JSONObject.parseObject(token);
        Map<String, Object> parseResult = JwtAccessTokenConverterUtils.decode(jsonObject.getString("access_token"));
        log.info("解析结果={}", parseResult);
        return token;
    }

    @GetMapping("/oauth2/refreshToken")
    public String refreshToken(String token) {
        return oAuth2Service.refreshToken("admin", "password", token);
    }

}
